package com.shy.configs.mvc.interceptors;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.shy.configs.common.clients.RedisClient;
import com.shy.configs.common.consts.Keys;
import com.shy.configs.common.enums.RCode;
import com.shy.configs.mvc.models.AjaxResult;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Resource
    private RedisClient redisClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.OPTIONS请求放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        //2.从请求头中获取token和loginId
        String loginId = request.getHeader("loginId");
        String authorization = request.getHeader("Authorization");
        if (StrUtil.isNotBlank(loginId) && StrUtil.isNotBlank(authorization) && authorization.startsWith("Bearer")) {
            //截取token
            String token = authorization.substring(7);
            String tokenKey = Keys.LOGIN_TOKEN_KEY + loginId;
            //从redis中获取token
            String redisToken = redisClient.getField(tokenKey,"jwt");
            //比对token
            if (StrUtil.isNotBlank(token) && token.equals(redisToken)) {
                return true;
            }
        }
        AjaxResult fail = AjaxResult.fail(RCode.FAIL_USER_TOKEN);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSONUtil.toJsonStr(fail));
        writer.flush();
        writer.close();
        return false;
    }
}
